package com.weixin.withdrawals;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.weixin.config.WxpayConfig;
import com.weixin.utils.MySSLSocketFactory;

public class WxWithdrawalsHttp {
	private static Logger logger=LoggerFactory.getLogger(WxWithdrawalsHttp.class);
	public static String httpsRequest(WxpayConfig wxpayConfig,String requestUrl, String body) throws Exception{
        HttpsURLConnection httpUrlConn=null;
		OutputStream os=null;
		BufferedReader br=null;
		String resStr=null;
		
		try {
			String acceptCharset=WxpayConfig.charset;
			String methodType="GET";
			if(body!=null){
				methodType="POST";
			}
			
			SSLSocketFactory ssl = MySSLSocketFactory.getSSLSocketFactory(wxpayConfig.getAgreement(),wxpayConfig.getKeyType(), wxpayConfig.getCertPath(), wxpayConfig.getMchId(),wxpayConfig.getKeyManager());
			HostnameVerifier hostVer=new HostnameVerifier() {	//主机名(域名校验)
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;	//信任所有主机
				}
			};

			URL url=new URL(requestUrl);
			httpUrlConn=(HttpsURLConnection)url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssl);
			httpUrlConn.setHostnameVerifier(hostVer);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
		    httpUrlConn.setRequestMethod(methodType);
		    httpUrlConn.setConnectTimeout(60000);
		    httpUrlConn.setReadTimeout(60000);
		    
		    httpUrlConn.connect();
		    
		    if("POST".equals(methodType)){
		    	if(!"".equals(body)){
		    		os=httpUrlConn.getOutputStream();
			    	os.write(body.getBytes(acceptCharset));
			    	os.flush();
		    	}
		    }
		    
		    br=new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(), acceptCharset));
		    String line=null;
		    StringBuilder sb=new StringBuilder();
		    while((line=br.readLine())!=null){
		    	sb.append(line);
		    }
		    
		    resStr=sb.toString();
		} finally{
			try {
				if(br!=null){
					br.close();
				}
				if(os!=null){
					os.close();
				}
				if(httpUrlConn!=null){
					httpUrlConn.disconnect();
				}
			} catch (IOException e) {
				logger.error("", e);
			}
		}
		return resStr;
    }
}
